import 'dart:convert';
import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:xin_he/page/login/model/xin_he_member_info_entity.dart';
import 'package:xin_he/utils/xin_he_event_bus.dart';
import 'package:xin_he/utils/xin_he_storage.dart';
import 'package:xin_he/utils/xin_he_toast.dart';

import '../page/login/model/xin_he_user_info_entity.dart';
import '../page/login/xin_he_login_action.dart';
import '../service/xin_he_reqest.dart';
import '../service/xin_he_url_class.dart';

///用户单例

class XinHeUserData extends ChangeNotifier {
  // static _instance，_instance会在编译期被初始化，保证了只被创建一次
  static final XinHeUserData _instance = XinHeUserData._internal();
  RxBool appLoginState = false.obs;
  RxString userId = ''.obs;
  ///用户token
  String? accessToken;

  ///个人信息接口获取用户详情数据模型
  XinHeMemberInfoEntity _userDetailInfo = XinHeMemberInfoEntity();
  Rx<XinHeMemberInfoEntity?> get userDetailInfo => _userDetailInfo.obs;


  ///用户token-
  // String? token;

  //提供了一个工厂方法来获取该类的实例
  factory XinHeUserData() {
    return _instance;
  }

  // 通过私有方法_internal()隐藏了构造方法，防止被误创建
  XinHeUserData._internal() {
    //收到登录成功事件通知
    bus.on(XinHeStorage.KdLoginSucNoti, (arg) {
      //登录成功后更新用户数据
      updateAllData();
    });
    //收到退出登录成功通知
    bus.on(XinHeStorage.KdUserLogoutNoti, (arg) {
      //退出成功后重置用户数据和app状态
      XinHeLoginAction.loginOutAndDelUserInfoData();
    });
    updateAllData();
  }

  ///更新所有用户资料
  Future updateAllData() async {
    //用户资料
    await updateUserInfoData();
    //app设置

  }

  Future updateUserInfoModel() async {
    // 初始化个人资料
    await XinHeLocalStorage.getJSON(XinHeStorage.userInfoData).then((value) {
      if (value == null) return;
      //取出本地字典
      Map myData = json.decode(value);
      //转换实例模型
      _userDetailInfo = XinHeMemberInfoEntity.fromJson(convertMap(myData));
    });

    // 初始化token
    await XinHeLocalStorage.get(XinHeStorage.accessToken).then((value) {
      accessToken = value;
      bus.emit(XinHeStorage.KdTokenUpdate);
    });

    await XinHeLocalStorage.get(XinHeStorage.userLoginStatus).then((value) {
      if (value == null) return;
      appLoginState.value = value;
    });

    await XinHeLocalStorage.get(XinHeStorage.userId).then((value) {
      if (value == null) return;
      userId.value = value;
    });
  }

  Map<String, dynamic> convertMap(Map<dynamic, dynamic> map) {
    map.forEach((key, value) {
      if (value is Map) {
        // it's a map, process it
        value = convertMap(value);
      }
    });
    // use .from to ensure the keys are Strings
    return Map<String, dynamic>.from(map);
    // more explicit alternative way:
    // return Map.fromEntries(map.entries.map((entry) => MapEntry(entry.key.toString(), entry.value)));
  }


  ///更新个人数据方法
  Future updateUserInfoData() async {
    var login = await XinHeLocalStorage.get(XinHeStorage.userLoginStatus);
    if (login == null) {
      return;
    }
    if (login is bool) {
      if (!login) {
        return;
      }
    }

    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);
    Map<String, dynamic> params = {'userId': userId};



    Map<String,dynamic>map = {

      'userId':userId

    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/member/findByMember',params: map,isPost: false);

    if(!result.result){
      return;
    }
    if(result.data['code'] == 0) {
      //存储用户数据
      await XinHeLocalStorage.setJSON(XinHeStorage.userInfoData, jsonEncode(result.data['data']));
      //更新model=
      await updateUserInfoModel();
      //更新用户信息成功发送全局通知
      bus.emit(XinHeStorage.KdUserInfoUpdateSuc);
    }else {
      XinHeToast.center(result.data['message']);
    }



  }

  Future delUserInfoAndAppInfo () async{
    //移除model数据
    _userDetailInfo = XinHeMemberInfoEntity();
    //清除本地数据
    await XinHeLocalStorage.set(XinHeStorage.userInfoData, '');
    //重置token
    xinHeUserData.accessToken = '';
    await XinHeLocalStorage.set(XinHeStorage.accessToken, '');
  }


}
XinHeUserData xinHeUserData= XinHeUserData();
